<?php
// +----------------------------------------------------------------------
// | 在我们年轻的城市里，没有不可能的事！
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | Author : Jansen <jansen.shi@qq.com>
// +----------------------------------------------------------------------
namespace jansen\utils\domain;
class Domain{

    /**
     * 取完整的后缀,如果是中文域名,则后缀前带idn三个字符
     * @param string $domain
     * @return string
     */
    public static function getFullSuffix(string $domain) {
        $domain = strtolower($domain);
        $suffix = self::getSuffix($domain);
        return (\jansen\utils\validator\Domain::isChineseName($domain) ? 'idn' : '') . $suffix;
    }

    /**
     * 不区分中文取后缀
     * @param string $domain
     * @return string
     */
    public static function getSuffix(string $domain) {
        $domain = strtolower($domain);
        return strstr($domain, '.');
    }

    /**
     * 取域名的名称
     * @param string $domain
     * @return string
     */
    public static function getDomainName(string $domain) {
        $domain = strtolower($domain);
        return strstr($domain, '.', true);
    }

    /**
     * 取域名名称长度,以字符为单位计算
     * @param string $domain
     * @return int
     */
    public static function getDomainNameLengthForChar(string $domain) {
        return strlen(self::getDomainName($domain));
    }

    /**
     * 取域名名称长度,以字为单位计算
     * @param string $domain
     * @return int
     */
    public static function getDomainNameLengthForWord(string $domain) {
        return mb_strlen(self::getDomainName($domain), 'UTF-8');
    }

    /**
     * 转换中文域名为punycode编码
     * @param string $domain
     * @return string
     */
    public static function encode(string $domain) {
        return (PHP_VERSION_ID < 70200)?idn_to_ascii($domain):idn_to_ascii($domain, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
    }

    /**
     * 将中文域名的punycode为中文文字
     * @param string $domain
     * @return string
     */
    public static function decode(string $domain) {
        $domain = strtolower($domain);
        return (PHP_VERSION_ID < 70200)?idn_to_utf8($domain):idn_to_utf8($domain, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
    }
}